<template>
    <div class="register-container">
        <div class="register-page-title">
            注册界面
        </div>
        <div class="register-form-box">
            <el-row :gutter="10">
                <el-col :span="10">
                    <el-form :rules="rules" :ref="registerForm" :model="LRUser" label-width="80px">
                        <el-form-item
                            prop="userName"
                            label="用户名"
                            :required="true">
                            <el-input v-model="LRUser.userName" placeholder=""></el-input>
                        </el-form-item>
                        <el-form-item
                            :required="true"
                            prop="password"
                            label="密码">
                            <el-input type="password" v-model="LRUser.password" placeholder="" show-password></el-input>
                        </el-form-item>
                        <el-form-item
                            :required="true"
                            prop="surePassword"
                            label="确认密码">
                            <el-input v-model="LRUser.surePassword" type="password" placeholder=""
                                      show-password></el-input>
                        </el-form-item>
                        <el-form-item
                            :required="true"
                            prop="email"
                            label="邮箱">
                            <el-input v-model="LRUser.email" placeholder=""></el-input>
                        </el-form-item>
                        <el-form-item label="验证码" :required="true" prop="verifyCode">
                            <el-row :gutter="10">
                                <el-col :span="11">
                                    <el-input v-model="LRUser.verifyCode" placeholder="输入邮箱验证码"></el-input>
                                </el-col>
                                <el-col :span="11">
                                    <el-button type="primary" size="mini" @click="sendEmailVerifyCode"
                                               v-text="sendVerifyBtnText" :disabled="sendVerifyBtnText !== '发送验证码'">
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item label="验证码" :required="true" prop="captcha">
                            <el-input v-model="LRUser.captcha" placeholder="输入验证码"
                                      @keyup.enter.native="doRegister"></el-input>

                            <img :src="captchaPath" alt="获取验证码失败"
                                 @click="updateCaptchaCode"
                                 class="captcha-code-cursor">
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="doRegister">注册</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>

import {
    checkCaptchaCode,
    checkEmailUnique,
    checkUserNameUnique,
    doRegister,
    sendEmailVerifyCode
} from "assets/api/userApi";
import {success_code} from "assets/utils/LRConstant";
import {hex_md5} from "assets/utils/md5";

export default {
    name: "index",
    data() {
        return {
            registerForm: 'registerForm',
            captchaPath: '',
            sendVerifyBtnText: "发送验证码",
            LRUser: {
                userName: "",
                password: "",
                surePassword: "",
                originalPassword: '',
                roles: "",
                avatar: "",
                email: "",
                sign: "",
                verifyCode: '',
                captcha: ''
            },
            rules: {
                userName: [
                    {required: true, message: '用户名不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkUserName, trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '密码不能为空', trigger: ['change', 'blur']},
                    {validator: this.validatePass, trigger: 'blur'}
                ],
                surePassword: [
                    {required: true, message: '请确认密码', trigger: ['change', 'blur']},
                    {validator: this.validatePass2, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '邮箱不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkEmail, trigger: 'blur'}
                ],
                verifyCode: [
                    {required: true, message: '邮箱验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkVerifyCode, trigger: 'blur'}
                ],
                captcha: [
                    {required: true, message: '验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkCaptchaCode, trigger: 'blur'}
                ],
            }
        }
    },
    methods: {
        checkCaptchaCode(rule, value, callback) {
            checkCaptchaCode(value).then((result) => {
                if (result.code === success_code) {
                    callback();
                } else {
                    callback(new Error("验证码不正确"));
                }
            })
        },
        resetForm() {
            this.$refs[this.registerForm].resetFields();
        },
        doRegister() {
            this.$refs[this.registerForm].validate((valid) => {
                if (valid) {
                    // console.log('submit!');

                    let user = {
                        password: hex_md5(this.LRUser.password),
                        userName: this.LRUser.userName,
                        email: this.LRUser.email
                    }
                    doRegister(this.LRUser.captcha, this.LRUser.verifyCode, user).then((result) => {
                        if (result.code === success_code) {
                            this.$message.success("注册成功");

                            location.href = '/login';
                        } else {
                            this.$message.error("注册失败 原因：" + result.message);
                        }
                    })
                } else {
                    console.log('error submit!!');
                }
            });
        },
        checkAge(rule, value, callback) {
            if (!value) {
                return callback(new Error('年龄不能为空'));
            }
            setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    if (value < 18) {
                        callback(new Error('必须年满18岁'));
                    } else {
                        callback();
                    }
                }
            }, 1000);
        },
        validatePass(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入密码'));
            }

            var patrn = /^[0-9]{1,20}$/;
            if (patrn.test(value)) {
                callback(new Error('不能纯数字'));
            }

            if (value.length < 6) {
                callback(new Error('密码不能少于6位'));
            }
            callback();
        },
        validatePass2(rule, value, callback) {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.LRUser.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        },
        checkEmail(rule, value, callback) {
            if (value === '') {
                callback(new Error('邮箱不能为空'));
            } else {
                const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

                if (!reg.test(value)) {
                    callback(new Error("邮箱格式不正确"));
                }

                checkEmailUnique(value, "").then((result) => {
                    if (result.code === 4043) {
                        callback();
                    } else {
                        callback(new Error(result.message));
                    }
                });
            }
        },
        checkVerifyCode(rule, value, callback) {
            if (value === '') {
                callback(new Error('邮箱验证码不能为空'));
            } else {
                callback();
            }
        },
        checkUserName(rule, value, callback) {
            if (value === '') {
                callback(new Error('用户名不能为空'));
            } else {
                checkUserNameUnique(value, "").then((result) => {
                    if (result.code === 4044) {
                        callback();
                    } else {
                        callback(new Error(result.message));
                    }
                });
            }
        },
        // 点击切换验证码
        updateCaptchaCode: function () {
            // 为节约资源 一直使用一个时间戳
            // 只有单人系统才能这么做
            // 但是会导致url 一直一样， vue 不会修改界面
            // 所以添加了一个随机参数 来改变url
            this.captchaPath = "/user/captcha?random=" + Date.parse(new Date());
        },
        sendEmailVerifyCode() {
            this.$refs[this.registerForm].clearValidate();

            this.$refs.registerForm.validateField("email", (val) => {
                // console.log(val);

                if (!val) {
                    sendEmailVerifyCode(this.LRUser.email).then((result) => {
                        if (result.code === success_code) {
                            // change ui
                            let clickBtnInterval = 15;

                            let interval = setInterval(() => {
                                clickBtnInterval--;
                                if (clickBtnInterval <= 0) {
                                    this.sendVerifyBtnText = "发送验证码";
                                    clearInterval(interval)
                                    return;
                                }

                                this.sendVerifyBtnText = "重新发送(" + clickBtnInterval + ")";
                            }, 1000);

                            this.$message.success("发送验证码成功")
                        } else {
                            this.$message.error("发送验证码失败 cause by:" + result.message);
                        }
                    });
                } else {
                    this.$message.warning("确认你的邮箱是否合法");
                }
            });
        }
    }
    ,
    mounted() {
        // init data
        this.updateCaptchaCode()
    }
}
</script>

<style scoped>
.register-form-box {
    margin-top: 20px;
}

.register-container {
    margin-top: 20px;
    padding: 20px;
    background-color: white;
}

.register-page-title {
    font-weight: 500;
    font-size: 20px;
}
</style>